<template>
  <div class="mqtt-client">
    <el-card class="box-card">
      <template #header>
        <div class="card-header">
          <h2>MQTT Client</h2>
          <el-tag :type="connectionStatus === 'Connected' ? 'success' : 'danger'">
            {{ connectionStatus }}
          </el-tag>
        </div>
      </template>

      <!-- 连接配置 -->
      <div class="connection-settings">
        <el-form :model="mqttConfig" label-width="120px">
          <el-form-item label="Broker URL">
            <el-input v-model="mqttConfig.url" :disabled="isConnected" />
          </el-form-item>
          <el-form-item label="Topic">
            <el-input v-model="mqttConfig.topic" :disabled="isConnected" />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="toggleConnection" :loading="connecting">
              {{ isConnected ? 'Disconnect' : 'Connect' }}
            </el-button>
          </el-form-item>
        </el-form>
      </div>

      <!-- 消息发送 -->
      <div class="message-sender" v-if="isConnected">
        <el-input
          v-model="messageToSend"
          placeholder="Enter message to send"
          :rows="3"
          type="textarea"
        />
        <el-button type="primary" @click="sendMessage" :disabled="!messageToSend" class="send-btn">
          Send Message
        </el-button>
      </div>

      <!-- 消息列表 -->
      <div class="message-list">
        <h3>Messages</h3>
        <el-timeline>
          <el-timeline-item
            v-for="(msg, index) in messages"
            :key="index"
            :type="msg.type === 'sent' ? 'primary' : 'success'"
            :timestamp="msg.timestamp"
          >
            <el-card class="message-card">
              <p><strong>{{ msg.type === 'sent' ? 'Sent' : 'Received' }}:</strong></p>
              <p>{{ msg.content }}</p>
            </el-card>
          </el-timeline-item>
        </el-timeline>
      </div>
    </el-card>
  </div>
</template>

<script lang="ts" setup>
import { ref, onUnmounted } from 'vue'
import mqtt from 'mqtt'
import type { MqttClient } from 'mqtt'

// 状态变量
const connectionStatus = ref('Disconnected')
const isConnected = ref(false)
const connecting = ref(false)
const client = ref<MqttClient | null>(null)
const messages = ref<Array<{ type: 'sent' | 'received', content: string, timestamp: string }>>([])
const messageToSend = ref('')

// MQTT配置
const mqttConfig = ref({
  url: 'ws://192.168.3.234:8083/mqtt',
  topic: 'test/topic'
})

// 连接/断开连接
const toggleConnection = async () => {
  if (isConnected.value) {
    // 断开连接
    client.value?.end()
    isConnected.value = false
    connectionStatus.value = 'Disconnected'
    return
  }

  // 建立连接
  connecting.value = true
  try {
    client.value = mqtt.connect(mqttConfig.value.url, {
      clientId: 'mqttjs_' + Math.random().toString(16).substr(2, 8),
      keepalive: 60,
      clean: true,
      connectTimeout: 4000,
      reconnectPeriod: 1000
    })

    client.value.on('connect', () => {
      isConnected.value = true
      connectionStatus.value = 'Connected'
      connecting.value = false
      
      // 订阅主题
      client.value?.subscribe(mqttConfig.value.topic, (err) => {
        if (err) {
          console.error('Subscribe error:', err)
        }
      })
    })

    client.value.on('message', (topic, message) => {
      messages.value.unshift({
        type: 'received',
        content: message.toString(),
        timestamp: new Date().toLocaleTimeString()
      })
    })

    client.value.on('error', (err) => {
      console.error('MQTT Error:', err)
      connectionStatus.value = 'Error'
      connecting.value = false
    })
  } catch (error) {
    console.error('Connection error:', error)
    connectionStatus.value = 'Error'
    connecting.value = false
  }
}

// 发送消息
const sendMessage = () => {
  if (!client.value || !messageToSend.value) return

  client.value.publish(mqttConfig.value.topic, messageToSend.value)
  messages.value.unshift({
    type: 'sent',
    content: messageToSend.value,
    timestamp: new Date().toLocaleTimeString()
  })
  messageToSend.value = ''
}

// 组件卸载时断开连接
onUnmounted(() => {
  if (client.value) {
    client.value.end()
  }
})
</script>

<style scoped>
.mqtt-client {
  max-width: 800px;
  margin: 20px auto;
  padding: 0 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.connection-settings {
  margin-bottom: 20px;
}

.message-sender {
  margin-bottom: 20px;
}

.send-btn {
  margin-top: 10px;
}

.message-list {
  margin-top: 20px;
}

.message-card {
  margin-bottom: 10px;
}

.el-timeline-item {
  margin-bottom: 20px;
}
</style> 